package com.neiru.divider.thread;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.neiru.divider.bean.Divider;
import com.neiru.divider.bean.Position;
import com.neiru.divider.bean.Section;
import com.neiru.divider.constants.Axis;
import com.neiru.divider.constants.ThreadConstants;

public class DividerThread extends Thread{
	private Section section;
	private Divider divider;
	private Boolean finishedStart = false;
	private Boolean finishedEnd = false;
	private Boolean finished = false;
	
	private boolean stop = false;
	
	private Handler dividerHandler = null;
	private Handler sectionHandler = null;
	
	private Integer step = 1;
	public DividerThread(Handler sectionHandler) {
		this.sectionHandler = sectionHandler;
	}
	@Override
	public void run() {
		if(this.divider == null || this.section == null) {
			return;
		}
		while(!finished && !divider.isCanceled() && !stop) {
			updatePosition();
			try {
				Thread.sleep(3);
			} catch (InterruptedException e) {
			}
			
		}
		if(finished) {
			Message removeDivider = new Message();
			removeDivider.what = ThreadConstants.REMOVE_FINISHED_MESSAGE;
			finishedEnd = false;
			finishedStart = false;
			finished = false;
			divider.setFinished(true);
			this.sectionHandler.sendMessage(removeDivider);
		} else if(divider.isCanceled()) {
			Message gameOverMessage = new Message();
			gameOverMessage.what = ThreadConstants.GAME_OVER;
			this.sectionHandler.sendMessage(gameOverMessage);
			
		}
		
	}
	
	private void updatePosition() {
		Position startPosition = divider.getStartPosition();
		Position endPosition = divider.getFinalPosition();
		if(Axis.AXIS_X.equals(divider.getAxis())) {
			if(startPosition.getX() > section.getLeft()) {
				startPosition.setX(startPosition.getX() - step);
			} else {
				finishedStart = true;
			}
			if(endPosition.getX() < section.getRight()) {
				endPosition.setX(endPosition.getX() + step);
			} else {
				finishedEnd = true;
			}
		} else {
			if(startPosition.getY() > section.getTop()) {
				startPosition.setY(startPosition.getY() - step);
			} else {
				finishedStart = true;
			}
			if(endPosition.getY() < section.getBottom()) {
				endPosition.setY(endPosition.getY() + step);
			} else {
				finishedEnd = true;
			}
		}
		finished = (finishedStart && finishedEnd);
	}
	
	public Section getSection() {
		return section;
	}
	public void setSection(Section section) {
		this.section = section;
	}
	public Divider getDivider() {
		return divider;
	}
	public void setDivider(Divider divider) {
		this.divider = divider;
	}
	
	public void killAllThreads() {
		this.stop = true;
	}
}
